package lk.icta.common.dao.impl;

import lk.icta.common.dao.PersonDAO;
import lk.icta.common.entity.Person;
import lk.icta.user.entity.User;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.Query;
import java.util.List;

/**
 * @author Duminda Dharmakeerthi
 */
public class PersonDAOImpl extends BaseDAO implements PersonDAO {

    @Transactional(propagation = Propagation.MANDATORY)
    public void addPerson(Person person, User user) {
        logger.debug("Adding a Person [Id: {}\tName: {}]", person.getId(), person.getName());
        em.persist(person);
    }

    @Transactional(propagation = Propagation.MANDATORY, readOnly = true)
    public Person getPersonById(long personId, User user) {
        logger.debug("Loading person [Id: {}]", personId);
        return em.find(Person.class, personId);
    }

    @Transactional(propagation = Propagation.NEVER, readOnly = true)
    public List<Person> getPersonByName(String name, User user) {
        logger.debug("Find person [Name: {}]", name);
        Query q = em.createNamedQuery("getPersonByName");
        q.setParameter("name", name);
        return q.getResultList();
    }

    @Transactional(propagation = Propagation.NEVER, readOnly = true)
    public Person getPersonByNIC(String nic, User user) {
        logger.debug("Find person [Name: {}]", nic);
        Query q = em.createNamedQuery("getPersonByNIC");
        q.setParameter("personNIC", nic);
        return (Person) q.getSingleResult();
    }

    @Transactional(propagation = Propagation.MANDATORY, readOnly = true)
    public void updatePerson(Person person, User user) {
        logger.debug("Updating a Person [Id: {}\tName: {}]", person.getId(), person.getName());
        em.merge(person);
    }

    @Transactional(propagation = Propagation.NEVER, readOnly = true)
    public List<Person> findAll() {
        logger.debug("Listing People");
        Query q = em.createNamedQuery("findAllPersons");
        return q.getResultList();
    }
}
